package com.topelec.smartstudio;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.topelec.zigbeecontrol.Command;
import com.topelec.zigbeecontrol.SensorControl;

import java.util.ArrayList;
import java.util.List;

import it.moondroid.coverflowdemo.R;


public class MainroomActivity extends Activity implements
        View.OnClickListener,
        SensorControl.LedListener,
        SensorControl.MotorListener,
        SensorControl.TempHumListener,
        SensorControl.LightSensorListener,
        SensorControl.PESensorListener {

    private static final String TAG = "MainroomActivity";
    private static final int REQ_SYSTEM_SETTINGS = 1;
    private boolean isLed1On;
    private boolean isLed2On;
    private boolean isLed3On;
    private boolean isLed4On;

    private int Temp;
    private int Hum;

    private boolean fanStatus = false;
    private boolean isBright;

//    private ImageButton btnLed1;
//    private ImageButton btnLed2;
//    private ImageButton btnLed3;
//    private ImageButton btnLed4;

    private ImageButton lightButton;
    private ImageButton windButton;
    private ImageButton dryButton;
    private ImageButton doorButton;
    private ImageButton windowButton;

    private List<ImageButton> arrayList = new ArrayList<ImageButton>();

    private TextView tempView;
    private TextView humView;

    private ImageView fanView;
    private ImageButton btnStart;

    private ImageView brightnessView;

    private Button btnSettings;
    private Button btnBack;
    private boolean isAutoTempHum;
    private boolean isAutoBrightness;
    private int settingTemperature;
    private int settingHumidity;


    SensorControl mSensorControl;

    private static final int TEMPERATURE_SENSOR = 31;
    private static final int HUMIDITY_SENSOR = 32;
    private static final int BRIGHTNESS_SENSOR = 40;

    //    private static final String TAG = ".EntryActivity";
    private static final double stepValue = -1.00;

    private ImageView statusView;
    private TextView idView;
    private TextView stepView;
    private TextView sumView;
    private boolean cardFlag = false;
    private int status = 0;
    /**
     * 用于同步UI,接受CardActivityGroup的broadcast
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            int what = intent.getExtras().getInt("what");
            switch (what) {
                case 1://初始化错误
                    //TODO:
//                    showMsgPage(R.drawable.buscard_consume_check_wrong,intent.getExtras().getString("Result"),"","");
//                    System.out.println("111111111111333333");
                    cardFlag = true;
                    break;
                case 2://未检测到卡
//                    hideMsgPage();
                    cardFlag = true;
//                    System.out.println("111111111111222222");
                    break;
                case 3: //成功获取卡号
                    if (cardFlag) {
                        String currentId = intent.getExtras().getString("Result");
                        System.out.println(currentId);
                        if (status == 0) {
                            start();
                            status++;
                            handlerFlag = true;
                        } else if (status == 1) {
                            status++;
//                            if (fanStatus) {
                            mSensorControl.fanStop(false);
                            mSensorControl.allLeds_Off(false);
                            fanStatus = false;
//                            }
                            empty();

//        mSensorControl.allLeds_Off(false);
                            handlerFlag = false;
                        } else {
                            status = 0;
                            ((CardActivityGroup) getParent()).clickResume();
                        }
                    }
                    // TODO:换场景
                    cardFlag = false;

                    break;
                default:
                    break;
            }
        }
    };

    private void hideMsgPage() {

        statusView.setImageDrawable(null);
        idView.setText("");
        stepView.setText("");
        sumView.setText("");
    }

    private void showMsgPage(int imageId, String cardId, String stepNum, String sumNum) {
        statusView.setImageDrawable(getResources().getDrawable(imageId));
        idView.setText(cardId);
        stepView.setText(stepNum);
        sumView.setText(sumNum);

    }

    /**
     * 用于更新UI
     */
    private boolean handlerFlag = false;
    Handler myHandler = new Handler() {
        //2.重写消息处理函数
        public void handleMessage(Message msg) {
            Bundle data;
            data = msg.getData();
            if (!handlerFlag) {
                return;
            }
            switch (msg.what) {
                // 判断发送的消息
                // led
                case 0x01:
                    switch (data.getByte("led_id")) {
                        case 0x01:
                            if (data.getByte("led_status") == 0x01) {
//                                btnLed1.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));

                                isLed1On = true;
                            } else {
//                                btnLed1.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
                                isLed1On = false;
                            }
                            break;
                        case 0x02:
                            if (data.getByte("led_status") == 0x01) {
//                                btnLed2.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
                                isLed2On = true;
                            } else {
//                                btnLed2.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
                                isLed2On = false;
                            }
                            break;
                        case 0x03:
                            if (data.getByte("led_status") == 0x01) {
//                                btnLed3.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
                                isLed3On = true;
                            } else {
//                                btnLed3.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
                                isLed3On = false;
                            }
                            break;
                        case 0x04:
                            if (data.getByte("led_status") == 0x01) {
//                                btnLed4.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
                                isLed4On = true;
                            } else {
//                                btnLed4.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
                                isLed4On = false;
                            }
                            break;
                        case 0x05:
                            if (data.getByte("led_status") == 0x01) {
//                                btnLed1.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
//                                btnLed2.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
//                                btnLed3.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
//                                btnLed4.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_on));
                                isLed1On = true;
                                isLed2On = true;
                                isLed3On = true;
                                isLed4On = true;
                            } else {
//                                btnLed1.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
//                                btnLed2.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
//                                btnLed3.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
//                                btnLed4.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_led_off));
                                isLed1On = false;
                                isLed2On = false;
                                isLed3On = false;
                                isLed4On = false;
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                // 马达
                case 0x02:
                    System.out.println("====222222====");
                    if (data.getByte("motor_status") == 0x01) {
//                        fanView.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_motor_start));
//                        btnStart.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_btn_motor_on));
                        fanStatus = true;
                    } else {
//                        fanView.setImageDrawable(null);
//                        btnStart.setImageDrawable(getResources().getDrawable(R.drawable.smarthome_btn_motor_off));
                        fanStatus = false;
                    }
                    break;
                // 温湿度
                case 0x03:
                    System.out.println("======123=======");
                    switch (data.getByte("senser_id")) {
                        case 0x01:
                            Temp = data.getInt("senser_data");
                            System.out.println("温度 ====== " + Temp);
                            tempView.setVisibility(View.VISIBLE);
                            tempView.setText("温度：" + String.valueOf(Temp));
                            //如下温度自动化管理代码
//                                if (Temp > settingTemperature) {
//                                    //TODO 温度大于设定值，降低温度，执行打开风扇动作
//                                    if (!fanStatus) {
//                                        mSensorControl.fanForward(true);
//                                        windButton.setImageDrawable(getResources().getDrawable(R.drawable.wind_on));
//                                    };
//                                } else {
//                                    //TODO 实时温度小于设定值，停止降低温度，如果此时风扇是运行状态，则执行停止风扇动作。
//                                    if (fanStatus) {
//                                        mSensorControl.fanStop(true);
//                                        windButton.setImageDrawable(getResources().getDrawable(R.drawable.wind_off));
//                                    }
//                                }
                            settingTemperature = 28;
                            if (Temp > settingTemperature) {
//                                    lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_on));
                                windButton.setImageDrawable(getResources().getDrawable(R.drawable.wind_on));
                                mSensorControl.allLeds_On(false);
                            } else {
//                                    lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_off));
                                windButton.setImageDrawable(getResources().getDrawable(R.drawable.wind_off));
                                mSensorControl.allLeds_Off(false);
                            }

                            break;
                        case 0x02:
                            // 湿度
                            Hum = data.getInt("senser_data");
                            System.out.println("湿度 ====== " + Hum);
                            humView.setVisibility(View.VISIBLE);
                            humView.setText("湿度：" + String.valueOf(Hum));
                            settingHumidity = 50;

//                            if (isAutoTempHum) {
                            if (Hum > settingHumidity) { // 开电机
//                                    if (!fanStatus) {
                                mSensorControl.fanForward(false);
                                dryButton.setImageDrawable(getResources().getDrawable(R.drawable.dry_on));
                                fanStatus = true;
//                                    };
                            } else { // 关电机
//                                    if (fanStatus) {
                                mSensorControl.fanStop(false);
                                dryButton.setImageDrawable(getResources().getDrawable(R.drawable.dry_off));
                                fanStatus = false;
//                                    }
                            }
//                            }
                            break;
                        default:
                            break;
                    }
                    break;
                //  光敏
                case 0x04:
                    // 白天
                    if (data.getByte("senser_status") == 0x01) {
                         lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_off));
                        //if (isAutoBrightness)
                        // 关灯，拉开窗帘（开马达）
                        mSensorControl.fanForward(false);
                        mSensorControl.allLeds_Off(false);
                        windowButton.setImageDrawable(getResources().getDrawable(R.drawable.window_on));
                        fanStatus = true;
                    } else { // 晚上
                         lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_on));
                        //if (isAutoBrightness)
                        // 开灯，马达停
                        mSensorControl.allLeds_On(false);
                        mSensorControl.fanStop(false);
                        windowButton.setImageDrawable(getResources().getDrawable(R.drawable.window_off));
                        fanStatus = false;
                    }
                    break;
                case 0x05:
                    if (data.getByte("senser_status") != 0x01) {
                        // 有人，开马达，亮灯
//                        if (!fanStatus) {
                        mSensorControl.fanForward(false);
                        doorButton.setImageDrawable(getResources().getDrawable(R.drawable.door_on));
                        lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_on));
                        fanStatus = true;
//                        }
                        mSensorControl.allLeds_On(false);
                    } else {
                        // 没人，关马达，熄灯
//                        if (fanStatus) {
                        mSensorControl.fanStop(false);
                        doorButton.setImageDrawable(getResources().getDrawable(R.drawable.door_off));
                        lightButton.setImageDrawable(getResources().getDrawable(R.drawable.light_off));
                        fanStatus = false;
//                        }
                        mSensorControl.allLeds_Off(false);
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //定义发送任务定时器
    Handler timerHandler = new Handler();
    Runnable sendRunnable = new Runnable() {

        @Override
        public void run() {
            int i = (int) System.currentTimeMillis() % 4 + 1;
            //TODO:查询温度湿度
            switch (i) {
                case 1:
                    mSensorControl.checkTemperature(true);
//                    i++;
                    break;
                case 2:
                    mSensorControl.checkHumidity(true);
//                    i++;
                    break;
                case 3:
                    mSensorControl.checkBrightness(true);
//                    i++;
                    break;
                case 4:
                    mSensorControl.checkPE(true);
//                    i = 1;
                    break;
                default:
                    break;
            }
            timerHandler.postDelayed(this, Command.CHECK_SENSOR_DELAY);
        }
    };

    private static final boolean AUTO_HIDE = true;
    private static final int UI_ANIMATION_DELAY = 300;
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    private final Handler mHideHandler = new Handler();

    //UI全屏显示
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };


    //显示程序中的底部控制按钮
    private View mControlsView;
    private View mBackView;
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {

            mControlsView.setVisibility(View.VISIBLE);
            mBackView.setVisibility(View.VISIBLE);
        }
    };


    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_smarthome);
        initialization();
        initSettings();
        mVisible = true;
        mControlsView = findViewById(R.id.smarthome_settings);
        mContentView = findViewById(R.id.smarthome_content);
        mBackView = findViewById(R.id.smarthome_back);


        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                toggle();
            }
        });

        mSensorControl = new SensorControl();
        mSensorControl.addLedListener(this);
        mSensorControl.addMotorListener(this);
        mSensorControl.addTempHumListener(this);
        mSensorControl.addLightSensorListener(this);
        mSensorControl.addPESensorListener(this);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
            delayedHide(AUTO_HIDE_DELAY_MILLIS);
        }
    }

    private void hide() {

        mControlsView.setVisibility(View.GONE);
        mBackView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    private void initialization() {
        isLed1On = false;
        isLed2On = false;
        isLed3On = false;
        isLed4On = false;

        Temp = 101;
        Hum = 101;

        fanStatus = false;
        isBright = true;


//        btnLed1 = (ImageButton) findViewById(R.id.btnLed1);
//        btnLed1.setOnClickListener(this);
//
//        btnLed2 = (ImageButton) findViewById(R.id.btnLed2);
//        btnLed2.setOnClickListener(this);
//
//        btnLed3 = (ImageButton) findViewById(R.id.btnLed3);
//        btnLed3.setOnClickListener(this);
//
//        btnLed4 = (ImageButton) findViewById(R.id.btnLed4);
//        btnLed4.setOnClickListener(this);

        this.lightButton = (ImageButton) findViewById(R.id.light_button);
        this.windButton = (ImageButton) findViewById(R.id.wind_button);
        this.dryButton = (ImageButton) findViewById(R.id.dry_button);
        this.doorButton = (ImageButton) findViewById(R.id.door_button);
        this.windowButton = (ImageButton) findViewById(R.id.window_button);

        this.arrayList.add(this.lightButton);
        this.arrayList.add(this.windButton);
        this.arrayList.add(this.dryButton);
        this.arrayList.add(this.doorButton);
        this.arrayList.add(this.windowButton);

        tempView = (TextView) findViewById(R.id.tempView);
        humView = (TextView) findViewById(R.id.humView);

        fanView = (ImageView) findViewById(R.id.fanView);
        btnStart = (ImageButton) findViewById(R.id.btnStart);
        btnStart.setOnClickListener(this);

//        brightnessView = (ImageView) findViewById(R.id.brightnessView);

        btnSettings = (Button) findViewById(R.id.btnSettings);
        btnSettings.setOnClickListener(this);

        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);

    }

    private void empty() {
        MainroomActivity.this.getWindow().setBackgroundDrawableResource(R.drawable.workshop_n);
        for (ImageButton i : this.arrayList) {
            i.setVisibility(View.INVISIBLE);
        }
        MainroomActivity.this.findViewById(R.id.tempView).setVisibility(View.INVISIBLE);
        MainroomActivity.this.findViewById(R.id.humView).setVisibility(View.INVISIBLE);
    }

    private void start() {
        MainroomActivity.this.getWindow().setBackgroundDrawableResource(R.drawable.workshop_d);
        for (ImageButton i : this.arrayList) {
            i.setVisibility(View.VISIBLE);
        }
        humView.setVisibility(View.VISIBLE);
        tempView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
//        case R.id.btnLed1:
//            if (isLed1On)
//            {
//                mSensorControl.led1_Off(false);
//            }else{
//                mSensorControl.led1_On(false);
//            }
//            break;
//        case R.id.btnLed2:
//            if (isLed2On)
//            {
//                mSensorControl.led2_Off(false);
//            }else{
//                mSensorControl.led2_On(false);
//            }
//            break;
//        case R.id.btnLed3:
//            if (isLed3On)
//            {
//                mSensorControl.led3_Off(false);
//            }else{
//                mSensorControl.led3_On(false);
//            }
//            break;
//        case R.id.btnLed4:
//            if (isLed4On)
//            {
//                mSensorControl.led4_Off(false);
//            }else{
//                mSensorControl.led4_On(false);
//            }
//            break;
//        case R.id.btnStart:
//            if (fanStatus)
//            {
//                mSensorControl.fanStop(false);
//            }else {
//                mSensorControl.fanForward(false);
//            }
//            break;
            case R.id.btnSettings:
                startActivityForResult(new Intent(this, Settings.class), REQ_SYSTEM_SETTINGS);
                break;
            case R.id.btnBack:
                finish();
                break;
        }
    }

    private void initSettings() {

        PreferenceManager.setDefaultValues(this, R.xml.settings_smarthome, false);
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        isAutoTempHum = settings.getBoolean("auto_temp_switch", true);
        isAutoBrightness = settings.getBoolean("auto_bright_switch", true);
        settingTemperature = Integer.parseInt(settings.getString("temp_settings", "27"));
        settingHumidity = Integer.parseInt(settings.getString("hum_settings", "40"));
        this.empty();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQ_SYSTEM_SETTINGS) {

            PreferenceManager.setDefaultValues(this, R.xml.settings_smarthome, false);
            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
            isAutoTempHum = settings.getBoolean("auto_temp_switch", true);
            isAutoBrightness = settings.getBoolean("auto_bright_switch", true);
            settingTemperature = Integer.parseInt(settings.getString("temp_settings", "27"));
            settingHumidity = Integer.parseInt(settings.getString("hum_settings", "40"));

        }

    }

    /**
     * 由不可见变为可见时调用
     */
    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(CardActivityGroup.recharge_action);
        registerReceiver(broadcastReceiver, filter);
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        mSensorControl.actionControl(true);

//        System.out.print("[onStart!!!]");

        //TODO:每350ms发送一次数据
        timerHandler.postDelayed(this.sendRunnable, Command.CHECK_SENSOR_DELAY);
    }

    /**
     * 在完全不可见时调用
     */
    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(broadcastReceiver);
        timerHandler.removeCallbacks(sendRunnable);
        mSensorControl.actionControl(false);

    }

    /**
     * 在活动销毁时调用
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        mSensorControl.removeLedListener(this);
        mSensorControl.removeMotorListener(this);
        mSensorControl.removeTempHumListener(this);
        mSensorControl.removeLightSensorListener(this);
        mSensorControl.removePESensorListener(this);
        mSensorControl.closeSerialDevice();
    }

    @Override
    public void LedControlResult(byte led_id, byte led_status) {

        Message msg = new Message();
        msg.what = 0x01;
        Bundle data = new Bundle();
        data.putByte("led_id", led_id);
        data.putByte("led_status", led_status);
        msg.setData(data);
        myHandler.sendMessage(msg);
    }

    @Override
    public void motorControlResult(byte motor_status) {

        Message msg = new Message();
        msg.what = 0x02;
        Bundle data = new Bundle();
        data.putByte("motor_status", motor_status);
        msg.setData(data);
        myHandler.sendMessage(msg);
    }

    @Override
    public void tempHumReceive(byte senser_id, int senser_data) {

        Message msg = new Message();
        msg.what = 0x03;
        Bundle data = new Bundle();
        data.putByte("senser_id", senser_id);
        data.putInt("senser_data", senser_data);
        msg.setData(data);
        myHandler.sendMessage(msg);
    }

    @Override
    public void lightSensorReceive(byte sensor_status) {

        Message msg = new Message();
        msg.what = 0x04;
        Bundle data = new Bundle();
        data.putByte("senser_status", sensor_status);
        msg.setData(data);
        myHandler.sendMessage(msg);
    }

    @Override
    public void peSensorReceive(byte sensor_status) {
        Message msg = new Message();
        msg.what = 0x05;
        Bundle data = new Bundle();
        data.putByte("senser_status", sensor_status);

        msg.setData(data);
        myHandler.sendMessage(msg);
    }
}
